using System.Globalization;
using System.Windows.Data;

namespace Koala.Pro.Helpers;

internal class NumericConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
        {
            return null;
        }
        if (targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(Nullable<>))
        {
            targetType = Nullable.GetUnderlyingType(targetType);
            return System.Convert.ChangeType(value, targetType);
        }
        if (!double.TryParse(value.ToString(), out var _))
        {
            return 0;
        }
        return System.Convert.ChangeType(value, targetType);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
        {
            return null;
        }
        if (!(value is string) && targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(Nullable<>))
        {
            targetType = Nullable.GetUnderlyingType(targetType);
            return System.Convert.ChangeType(value, targetType);
        }
        if (!double.TryParse(value.ToString(), out var result))
        {
            return DBNull.Value;
        }
        return result;
    }
}
